// pages/czqhome/czqhome.js

import {
  picUrl,
  formatTime,
  launchAppCopy,
  dataHandleNull
} from '../../utils/util.js';
import {
  indexFeed2,
  tagsList,
  getUserH5Openid
} from '../../utils/getData.js'
const getopen = require('../../utils/maxutil.js');

const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {

    isliuhai:app.globalData.isliuhai, //是否有刘海
    headerTop:getApp().globalData.headerTop, //导航距离顶部的距离
    //头部数据
    curMeal:0,
    headerDataList:[],//顶部类型
    headerSeletData:{},//选择类型
    minModel: app.globalData.minModel, //小机型iphone8
    current: 0, //改变当前索引
    itemIndex: 0, //当前索引
    isLock: false,
    requsetSize: 0,
    pageNum: 1,
    list: [],

    maTop: '', // m-a应往下多少

    swiperstart: '', // 触摸开始的坐标点
    swipernum: '', // 触摸结束的坐标点
    leftnumber: 132, //偏移数量
    currentnumber: 2, //当前局
    moreArrow: false, //左滑查看更多
    isair: false, //左边空格占位

    isCardShow: false, //
    cardData: [], //
    goAppPopover: false, //进入有局app弹框状态

    swiperHeight: 77, // swiper的高度 
    // swiper的两侧宽度
    preWidth: 70,
    nextWidth: 70,

    cardTop: 2, // 卡片距离顶部的高度
    isShowBottom: true, // 是否显示卡片底部按钮
    allowMove: true, // 是否允许执行移动函数
    cardButonWidth: '100%', // 底部宽度

    activityId:'',//
    hasActiveData:{},
    noActiveData:{}

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let activityId = '';
    const that = this;
    //扫码进来
    if (options.scene) {
      activityId = options.scene //decodeURIComponent(options.scene)
    }
    //页面内跳入
    if (options.activityId) {
      activityId = options.activityId
    }
    this.setData({
      activityId:activityId
    },()=>{
      //是否登录
      if (wx.getStorageSync('userId')) {
        this.getTagsListData();
      } else {
        this.login();
      }

    })
    // 获取设备宽高
    wx.getSystemInfo({
      success: (result) => {
        that.setData({
          maTop: (result.statusBarHeight * 2) + 80,
        });
        if (result.screenHeight > 736) {
          that.setData({
            swiperHeight: 61,
          });
        }
      },
    })

    this.monitorCardStyle();

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  //登录
  login() {
    getopen.loginOpenid().then(res => {
      console.log('取到了openid')
      this.getTagsListData();
    })
  },

  getIndexFeedTwo() {
    const { activityId } = this.data
    let than = this;
   //activityId有值时入参
    // let data = {
    //   userId: wx.getStorageSync('userId'), //
    //   pageNum: than.data.pageNum,
    //   objectId:activityId,
    //   conferenceType:2, //是否普通局，默认传2
    //   pageSize: 3,
    //   tags: '1,2,3,4,5',
    //   todayFlag: 2,
    //   guanzhuFlag: 0
    // }
    //activityId无值时入参
    // let datatwo = {
    //   userId: wx.getStorageSync('userId'), //
    //   pageNum: than.data.pageNum,
    //   pageSize: 3,
    //   tags: '1,2,3,4,5',
    //   todayFlag: 2,
    //   guanzhuFlag: 0
    // }
    
    this.setData({
      hasActiveData:than.data.hasActiveData,
      noActiveData:than.data.noActiveData
    })


    

    indexFeed2(activityId ? this.data.hasActiveData :this.data.noActiveData).then(res => {
      

      if (res.success) {
        than.setData({
          requsetSize: res.result.total
        })
        let conferenceData = res.result.records;
        let coordinate = 0; //坐标，当前局所在位置
        //  let ids = [];

        console.log(conferenceData);

        //判断局是否结束
        let currentTime = formatTime(new Date()); //当前时间
        currentTime = currentTime.substring(0, currentTime.length - 9);

        let newDatd = conferenceData.map((item, index) => {
           item = dataHandleNull(item); 
          if (activityId == item.conferenceId) {
            coordinate = index
            // coordinate = 0;
          }
          let activityEndTime = item.conferenceDate.slice(0,10).replace(/-/g, "/"); //局结束时间
          console.log(item.activityMoney)
          console.log(currentTime > activityEndTime)
          let payWay = "所有人AA";
          if(item.conferencePayWay==2){
            payWay = "男生AA";
          }else if(item.conferencePayWay==3){
            payWay = "女生AA";
          }else if(item.conferencePayWay==4){
            payWay = "我请客";
          }
          let tt = "￥"+item.conferenceAmount+"/人"+"\xa0\xa0\xa0"+payWay;
          
          
          return {
            activityInvalidation: currentTime > activityEndTime, //局是否失效
            activityBlurCoverPage: picUrl('activity/img/', item.conferenceBlurCoverPage),
            activityCoverPage: picUrl('activity/img/', item.conferenceCoverPage),
            activityAddress: item.conferenceAddress.split(',')[0],
            activityBeginTime: item.conferenceBeginTime,
            activityDate: item.conferenceDate.slice(5).replace(/-/g, "/"),
            activityEndTime: item.conferenceEndTime,
            activityId: item.conferenceId,
            activityImageRGB: item.conferenceRGB, //
            activityJoinType: item.conferenceJoinType,
            activityMaxNums: item.conferenceMaxNums,
            activityName: item.conferenceName,
            activityRGB: item.conferenceRGB,
            
            activityTips:item.conferenceTips.split(","),
            conferenceType: item.conferenceType, //是否为大型活动
            islock: false, //是否为第一次跳转大型活动， false--未锁定  true--锁定
            activityMoney:tt, //
            guanzhu: item.guanzhu, //
            guanzhuTips: item.guanzhuTips, //
            
            userTips: item.userTips, //
            userTagNames:item.userTagNames,//标签
            userTagName:this.data.headerSeletData.content,
            join: item.conferenceType ==1 ? false :item.join, //
            shareImg: picUrl('activity/img/', item.shareImg), //
            activityUsedNums: item.conferenceUsedNums,
            activityUserMap:item.conferenceUserMap.participantlist,

            sponsorId: item.sponsorId,
            sponsorUser: {
              ...dataHandleNull(item.sponsorUser) ,
              avatarPath: picUrl('', item.sponsorUser.avatarPath),
              authImgPath: picUrl('activity/img/', item.sponsorUser.authImgPath),
              userPic: picUrl('activity/img/', item.sponsorUser.userPic)
            },

          }
        })
        let newDatdtwo = newDatd.map((b) => {7
          return {
            ...b,
            activityUserMap: b.activityUserMap && b.activityUserMap.map((c) => {
              return {
                ...dataHandleNull(c),
                authImgPath: picUrl('', c.authImgPath),
                avatarPath: picUrl('', c.avatarPath),
                userPic: picUrl('', c.userPic)
              }
            })
          }
        })
        console.log("===="+newDatdtwo)

        than.setData({
          // list: newDatdtwo,
          list: than.data.list.concat(newDatdtwo),
          // cardData: newDatdtwo[coordinate],
          leftnumber: (coordinate + 2) * 66,
          currentnumber: coordinate,
          // current:coordinate
        }, () => {
          than.setData({
            isloading: false, //加载完成
            isCardShow: true,
            activityCoverPage: than.data.list[than.data.current].activityCoverPage,
          })
          wx.setStorageSync('lookCoverPage', than.data.list[than.data.current].activityCoverPage); //在看的主题图片(局或者活动)，登录流程需要用到
        })


        //  than.getActivityDetail();
      }
    })
    
    
  },

  getTagsListData(){

    let than = this;

    tagsList().then(res=>{
      if (res.success) {
        
        
        let seletdata = {
          "id": "1,2,3,4,5,6,7",
          "createTime": null,
          "createUser": "",
          "updateTime": null,
          "updateUser": "",
          "version": 0,
          "status": 1,
          "type": "全部",
          "content": "全部",
          "imgPath": "bd3.png",
          "typeSort": "3",
          "tagSort": "1"
        }
       let arr = [seletdata];
       arr = [...arr,...res.result]
        than.setData({
          headerDataList:arr,
          
        },()=>{
          if(res.result.length>0){
            let data = {
              userId: wx.getStorageSync('userId'), //
              pageNum: 1,
              objectId:than.data.activityId,
              conferenceType:2, //是否普通局，默认传2
              pageSize: 3,
              tags: seletdata.id,
              todayFlag: 2,
              guanzhuFlag: 0
            }
            //activityId无值时入参
            let datatwo = {
              userId: wx.getStorageSync('userId'), //
              pageNum: 1,
              pageSize: 3,
              tags: seletdata.id,
              todayFlag: 2,
              guanzhuFlag: 0
            }
            than.setData({
              headerSeletData:seletdata,
              hasActiveData:data,
              noActiveData:datatwo
            });

            than.getIndexFeedTwo();
            
          }
        })
      }


    });
  },
  

  

   //类型切换
   selectMeal(e){
    
    
    console.log(wx.getStorageSync('userId'),e);
    this.setData({
      headerSeletData:e.target.dataset.selet,
      list:[],
      pageNum:1

    },()=>{
      let data = {
        userId: wx.getStorageSync('userId'), //
        pageNum: 1,
        objectId:this.data.activityId,
        conferenceType:2, //是否普通局，默认传2
        pageSize: 3,
        tags: e.target.dataset.selet.id,
        todayFlag: 2,
        guanzhuFlag: 0
      }
      //activityId无值时入参
      let datatwo = {
        userId: wx.getStorageSync('userId'), //
        pageNum: 1,
        pageSize: 3,
        tags: e.target.dataset.selet.id,
        todayFlag: 2,
        guanzhuFlag: 0
      }
      
      this.getIndexFeedTwo();

    }
    )
   
  },

 
  //专题活动跳转
  todetail() {
    console.log("aaa111"),
    wx.vibrateLong()
    wx: wx.navigateTo({
      url: '../bureau/bureau?conventionId=4e02a53a123b4594b38249bba1c3273f'
    })
  },

  //局详情数据
  getActivityDetail() {
    const {
      list,
      currentnumber
    } = this.data;
    let current = this.data.current

    // if (current == this.data.list.length - 1) current = 1
    // else if (current == this.data.list.length - 2) current = 0
    // else current = current + 2

    

    let activityId = list[current].conferenceId
    // let activityId = list[currentnumber].activityId
    let than = this;

    // let current = list[currentnumber];

    than.setData({
      cardData: list[current], //卡片上的数据
      // activityCoverPage: list[current].activityCoverPage,
    }, () => {
      than.setData({
        isloading: false, //加载完成
        isCardShow: true,
      })
      // than.getIndexFeedTwo();
    })

    if (list[current].conferenceType == 1) {
      if (!list[current].islock) {
        list[current].islock = true;
        wx.navigateTo({
          url: '../bureau/bureau?conventionId=' + list[current].activityId
        })
      }
    }

  },
  touchSwiper(e) {
    // console.log(e);
    if (this.data.allowMove) {
      this.setData({
        isShowBottom: false, // 滑动时隐藏卡片底部按钮
        allowMove: false, // 该次滑动内不再执行此方法
      });
    }
  },
  touchSwiperEnd(e) {
    // 如果松手以后也显示底部按钮
    setTimeout(() => {
      this.setData({
        isShowBottom: true,
        allowMove: true,
      });
    }, 100);
  },
  monitorCardStyle() {
    let than = this;
    // 获取设备宽度高度对卡片内属性进行计算
    wx.getSystemInfo({
      success(res) {
        if (res.screenWidth <= 375) {
          than.setData({
            preWidth: 80,
            nextWidth: 52,
            cardButonWidth: '95%',
          });
        } else if (res.screenWidth > 375 && res.screenWidth < 414) {
          than.setData({
            preWidth: 78,
            nextWidth: 66,
            cardButonWidth: '98%',
          });
        } else if (res.screenWidth >= 414) {
          than.setData({
            preWidth: 60,
            nextWidth: 82,
            cardButonWidth: "104%",
          });
        }
      }
    });
  },
  changetwo(e) { //滑动切换索引
    console.log('1111',e)
    let that = this
    let {
      list
    } = that.data
    if (e.detail.source == 'touch') {
      that.setData({
        current: e.detail.current,
        activityCoverPage: list[e.detail.current].activityCoverPage
      })

      wx.setStorageSync('lookCoverPage', list[e.detail.current].activityCoverPage); //在看的主题图片(局或者活动)，登录流程需要用到
      console.log(list)
      if (e.detail.current == that.data.list.length - 2) {
        if (that.data.list.length < that.data.requsetSize) {
          that.setData({
            pageNum: that.data.pageNum + 1
          })
          that.getIndexFeedTwo()
        }
      }
       if (list[e.detail.current].conferenceType == 1) {
        if (!list[e.detail.current].islock) {
          console.log("11111:")
          list[e.detail.current].islock = true;
          wx.navigateTo({
            url: '../bureau/bureau?conventionId=' + list[e.detail.current].activityId
          })
        }
      }

      that.monitorCardStyle();

      // 在数据加载完成后 200毫秒后显示卡片底部按钮
      setTimeout(() => {
        that.setData({
          isShowBottom: true, // 显示底部按钮
        });
      }, 200);

      wx.vibrateShort();
    }
    // if (that.data.isLock) {

    // }

  },

  swiperItem(e) { //点击切换索引
    // this.data.current=index
    this.setData({
      isLock: false
    })
    let len = this.data.list.length
    var index = 0
    if (e.currentTarget.dataset.index == 0) {
      index = len - 2
    } else {
      index = (e.currentTarget.dataset.index - 2 < 0) ? (len - e.currentTarget.dataset.index) : (e.currentTarget.dataset.index - 2)
    }
    // console.log(e.currentTarget.dataset.index)
    this.setData({
      current: index
    })
    this.getActivityDetail()
    wx.vibrateShort();
    // console.log(this.data.current)
  },
  

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  //点导航
  onConference(e) {
    let than = this;
    const {
      list
    } = this.data;
    let cur = e.currentTarget.dataset.index;
    if (list[cur].conferenceType == 1) {
      wx.navigateTo({
        url: '../bureau/bureau?conventionId=' + list[cur].activityId
      })
    } else {
      this.setData({
        leftnumber: cur * 66 + 66 * 2,
        currentnumber: cur
      }, () => {
        than.getActivityDetail()
      })
    }
  },

  //  打开有局app弹框
  openApp() {
    wx.vibrateShort();

    //是否安卓机
    if (!app.globalData.isiPhone) {
      wx.navigateTo({
        url: '../androidMessage/androidMessage'
      })
      return false
    }
    console.log('打开有局app')
    this.setData({
      goAppPopover: true
    })
  },
  //有局app弹框上的按钮事件
  launchAppError(e){
    console.log(7777)
    //复制文字到剪贴板
    launchAppCopy()
  },

  //透明背景事件
  ontransparentBj() {
    this.setData({
      goAppPopover: false
    })
  },

  //进入个人主页
  goHome() {
    wx.vibrateShort();

    if (wx.getStorageSync('status') == 0) {
      //未注册的用户
      wx.navigateTo({
        url: '../login/login'
      })
    } else {
      wx.navigateTo({
        url: '../homepage/homepage'
      })

    }

  },
  /**
   * 用户点击分享
   */
  onShareAppMessage: function () {
    return {
      path: 'pages/subBureauDetails/subBureauDetails?activityId='+this.data.list[this.data.current].activityId,
      imageUrl: this.data.list[this.data.current].shareImg,
    };

    // 用户点击右上角分享给好友,要先在分享好友这里设置menus的两个参数,才可以分享朋友圈
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },

  //用户点击右上角分享朋友圈
  onShareTimeline: function () { 
      return {
          path: 'pages/subBureauDetails/subBureauDetails?activityId='+this.data.list[this.data.current].activityId,
          imageUrl: this.data.list[this.data.current].shareImg,
        }
    },

})